<?php
class TrainingController extends Zend_Controller_Action {
	public function init() {
		$ajaxContext = $this->_helper->getHelper('AjaxContext');
		$ajaxContext->addActionContext('categories','json');
		$ajaxContext->addActionContext('commune','json');
		$ajaxContext->addActionContext('selected','json');
		$ajaxContext->addActionContext('nextpage','json');
		$ajaxContext->addActionContext('search','json');
		$ajaxContext->initContext();
	
	}
	
	public function indexAction() {
		if($this->_helper->Acl->getUser()->getRole()==Core_Business_Rule::Customer)
			$filter = array("createdBy = ?"=>Core_Common_Controllers_Actions_Helpers_Acl::getUserId());
		else 
			$filter=null;
		$session = new Zend_Session_Namespace('paginator');
		$paginator = Core_Business_Training::getTrainingIterator($filter);
		
		$out =array();
		foreach ($paginator->getPages() as $item) {
			if($item->Paymentid != null) {
				$pay = $item->getPayment()->Label;
			}
			else { 
				$pay = "-";
			}
			//$pay = isset($item->getPayment()) ? $item->getPayment()->Label:"-";
			$out[]=array("id"=>$item->Id,"title"=>$item->Name,"payment"=>$pay,"Rule"=>$this->_helper->Acl->getUser()->getRole(),"User"=>$this->_helper->Acl->getUser()->LastName,"Created"=>$item->Created);	
		}
		$expertises = Core_Business_Expertises::getAll();
		$tbExpertises = array("NULL"=>"Selectionner");
		foreach ($expertises as $expertise) {
			$tbExpertises[$expertise->Category][$expertise->Id] =$expertise->Name; 	
		}
		$payments = Core_Business_Payment::getAll();
		$lstpayment = array();
		if(isset($payments)) {
			$lstpayment[""]="Remuneration";
			foreach ($payments as $pay) {
				$lstpayment[$pay->Id]=$pay->Label;	
			}
		}
		$this->view->metier = $tbExpertises;
		$this->view->payments = $lstpayment;
		$session->paginator = $paginator;
		$this->view->list=$out;

		$this->view->paginator = $paginator;
	}
	public function showAction() {
		
		if(!$this->getRequest()->get('id'))
			$this->_redirect('/default/training/index');
		$id = $this->getRequest()->get('id');
		$training = Core_Business_Training::getById($id);
		$this->view->training = $training;
		$this->view->rule = $this->_helper->Acl->getUser()->getRole();
		if($this->_helper->Acl->getUser()->getRole()==Core_Business_Rule::Customer) {
			$candidates = Core_Business_Trainingcandidate::getAllCandidate($id);
			$listcandidate=array();
			$choose = Core_Business_Trainingcandidate::getPostule($id);
			$haveselectedTrainer = isset($choose) ? true : false;
			foreach ($candidates as $item) {
				$user = Core_Business_User::getById($item->Userid);
				$listcandidate[]=array("trainingid"=>$id,"userid"=>$user->Id,"Nom"=>$user->Lastname,"Prenom"=>$user->Firstname,"choose"=>$item->IsSelect,"TranerSelect"=>$haveselectedTrainer);
			}
			$this->view->candidates = $listcandidate;
		}
		
		if($this->_helper->Acl->getUser()->getRole()==Core_Business_Rule::Trainer) {
			$hastrainer = $training->hasTrainer();
			$alreadyPostulate = Core_Business_Trainingcandidate::isPostulate($id, $this->_helper->Acl->getUser()->Id);
			$this->view->alreadyPostulate=$alreadyPostulate;
			$this->view->hastrainer=$hastrainer;
		}
		
	}
	public function selectedAction() {
		if($this->getRequest()->isGet()){
			$userid = $this->getRequest()->getParam('userid');
			$trainingid = $this->getRequest()->getParam('trainingid');
			
			$candidate = Core_Business_Trainingcandidate::getPostulate($trainingid,$userid);
			$candidate->IsSelect = 1;
			$candidate->save();
			$output = array("output"=>"success");
		}
		else 
		$output = array("output"=>"failed");
		
		$this->view->output = Zend_Json_Encoder::encode($output);
	}
	public function postulateAction(){
		if($this->getRequest()->isPost() && $this->_helper->Acl->getUser()->getRole()==Core_Business_Rule::Trainer) {
			$candidate=new Core_Business_Trainingcandidate();
			$candidate->Trainingid = $this->getRequest()->getPost('trid');
			$candidate->Userid = $this->_helper->Acl->getUser()->getId();
			$candidate->save();
		}
		$this->_redirect("/training/index");
	}
	public function addAction() {
		$this->initForm();
	}
	
	protected function initForm() {
		//$TrainingCategoryCollection = Core_Business_Category::getAll();
		$TrainingExpertisesCollection = Core_Business_Expertises::getAll();
		$categories = array(""=>"Selectionner");
		foreach ($TrainingExpertisesCollection as $item) {
			$categories[$item->Category][$item->Id] = $item->Name;
		}
	   //$tbExpertises = array("NULL"=>"Selectionner");
		$payments = Core_Business_Payment::getAll();
		$lstpayment = array();
		if(isset($payments)) {
			$lstpayment[""]="Remuneration";
			foreach ($payments as $pay) {
				$lstpayment[$pay->Id]=$pay->Label;	
			}
		}
		
		//$this->view->form=array("categories" => $categories);
		//$dep = Core_Business_Zone::getAllDepatement();
		//$departements = array();
		
		/*foreach ($dep as $item) {
			$departements[$item->Dep] = $item->Departement;
		}
		$sdep = array_flip($departements);
		$ssdep = $sdep !=null ? array_multisort($sdep) : null;
		$departements = $ssdep ? array_flip($sdep) : $departements;*/
		
		$this->view->form=array("categories" => $categories,"payment"=>$lstpayment);
	}
	
	public function editAction() {
		if ($this->getRequest()->isGet()) {
			$trainingid = $this->getRequest()->getParam('id');
			$training = isset($trainingid) ? Core_Business_Training::getById($trainingid) : null;
			if ($training !==null) {
				$this->initForm();
				$expertises = $training->Expertises;
				$catid = isset($expertises) ? $expertises : null;
				$formdata = array("id"=>$training->Id,"name"=>$training->Name,"category"=>$catid,"detail"=>$training->Detail,'trpayment'=>$training->Paymentid);
				$zones = $training->getAllZone();
				$selectedzone=array();
				$selectedzoneval=array();
				foreach ($zones as $zone) {
					//var_dump($zone);die;
					$z = Core_Business_Zone::getByCodeinsee($zone->Codeinsee);
					$z = current($z);
					$selectedzoneval[]=$zone->Codeinsee;
					$selectedzone[$zone->Codeinsee]=$z->Commune;
				}
				$selectedexp = array();
				if(isset($expertises )){
					$expertises = is_array($expertises)?$expertises : array($expertises);
					foreach ($expertises as $exp) {
						$selectedexp[] = $exp->Expertiseid;
					}
				}
				$formdata['selectedzone']=$selectedzone;
				$formdata['selectedzoneval']=$selectedzoneval;
				$formdata['selectedexpertise'] = $selectedexp;
				$this->view->form['formdata']=$formdata;
			}
			else {
				$this->_redirect('/training/index');
			}
				
		}
	}
	
	public function saveAction() {
		if($this->getRequest()->isPost()) {
			//var_dump($this->getRequest()->getPost());die;
			$userid = Core_Common_Controllers_Actions_Helpers_Acl::getUserId();
			$id = $this->getRequest()->getPost();
			$id = isset($id['id']) && $id['id']<>''? $id['id'] : null;
			$departements = $this->getRequest()->getPost('departement');
			$communes = $this->getRequest()->getPost('commune');
			$expertise = $this->getRequest()->getPost('expertises');
			$payment = $this->getRequest()->getPost('trainingPayment');
			//var_dump($expertise);die;
			$zone = isset($communes) && is_array($communes) && count($communes)>0 ? $communes : Core_Business_Zone::getByDep($departements);	 	
			
			$training = new Core_Business_Training();
			$training->setName($this->getRequest()->getPost('trainingName'));
			$training->setDetail($this->getRequest()->getPost('trainingDetails'));
			$training->setExpertises($expertise);
			if($payment!=Core_Business_Payment::ZERO)
				$training->setPaymentid($payment);
			$training->setCreatedBy($userid);
			$training->setZone($zone);
			$training->setId($id);
			$training->save();
			$this->_redirect('/training/index');
		}
		
	}
	
	public function categoriesAction() {
		if($this->getRequest()->isGet()) {
			$this->_helper->layout->disableLayout();
			$parentid = $this->getRequest()->getParam('parentid');
			
			$categories = Core_Business_Category::getCategoryByParent($parentid);
			
			$output = array();
			foreach ($categories as $category) {
				$output[] = array("id"=>$category->Id,"name"=>$category->Name);
			}
			$this->view->output = Zend_Json::encode($output);
			//$this->_helper->viewRenderer->setNoRender(true);
		}
	}
	public function communeAction() {
		if($this->getRequest()->isGet()) {
			$this->_helper->layout->disableLayout();
			$dep = $this->getRequest()->getParam('dep');
			$dep = is_array($dep) ? $dep[0]:$dep ;
			//$dep = explode(',', $dep);
			//$communes = Core_Business_Zone::getByDep($dep);
			$communes = Core_Business_Zone::searchZone($dep);
			$output = array();
			if(count($communes)>0) {
			foreach ($communes as $commune) {
				$output[]=array("value"=>$commune->Insee,"label"=>$commune->Commune);
			}
			}
			$this->view->output = Zend_Json::encode($output);
		}
	}
	
	public function nextpageAction() {
		if($this->getRequest()->isGet()) {
			$this->_helper->layout->disableLayout();
			$pagenum = $this->getRequest()->getParam('page');
			$session = new Zend_Session_Namespace('paginator');
			$paginator = $session->paginator;
			$out =array();
			$editable  =$this->_helper->Acl->getUser()->getRole() == Core_Business_Rule::Customer ? true : false;
			$rows = $paginator->getPages(intval($pagenum));
			foreach ($rows as $item) {
				if($item->Paymentid != null) {
					$pay = $item->getPayment()->Label;
				}
				else { 
					$pay = "-";
				}
				$out[]=array("id"=>$item->Id,"title"=>$item->Name,"payment"=>$pay,"Rule"=>$this->_helper->Acl->getUser()->getRole(),"User"=>$this->_helper->Acl->getUser()->LastName,"Created"=>$item->Created);	
			}
			$this->view->output = Zend_Json::encode($out);	
		}
	}
	
	public function searchAction(){
		if($this->getRequest()->isPost()) {
			$this->_helper->layout->disableLayout();
			$searchkey = trim($this->getRequest()->getPost('key'));
			$searchkey = str_replace('*','%',$searchkey);
			$datedebut = trim($this->getRequest()->getPost('datedebut'));
			$datefin = trim($this->getRequest()->getPost('datefin'));
			$zip = trim($this->getRequest()->getPost('zip'));
			$expertises = trim($this->getRequest()->getPost('exp'));
			$payfloor = trim($this->getRequest()->getPost('payment'));
			$paymentop = trim($this->getRequest()->getPost('paymentop'));
			$payroof = trim($this->getRequest()->getPost('paymenroof'));
			$query = array();
			if(isset($searchkey)&& $searchkey!="")
				$query["name like ?"] = $searchkey;
			
			if(isset($datedebut) && $datedebut!="")
				$query["created >= ?"] = $datedebut;
			if(isset($datefin) && $datefin!="")
				$query["created <= ?"] = $datefin;
				
			if($this->_helper->Acl->getUser()->getRole()==Core_Business_Rule::Customer)
				$query["CreatedBy = ?"]=$this->_helper->Acl->getUser()->Id;
			if(isset($zip) && $zip!=''&&count($zip)>0) {
				$query["id IN (SELECT trainingid FROM `trainingzone` WHERE codeinsee IN (?))"]=explode(",", $zip);
			}
			if($expertises!="" && $expertises!="null") {
				$query["id in (SELECT trainingid FROM `trainingexpertise` WHERE expertiseid IN (?))"]=explode(",", $expertises);
			}
			if(isset($payfloor)&&$payfloor!="") {
				if($paymentop=="Between") {
					$query["paymentid >= ?"]=$payfloor;
					$query["paymentid <= ?"]=$payroof;
				}
				else {
					switch ($paymentop) {
						case "eq":
						$op = " = ?";
						break;
						case "lte":
						$op = " <= ?";
						break;
						case "gte":
						$op = " >= ?";
						break;
						default:
						$op = " = ?";
						break;
					}
				$query["paymentid".$op]=$payfloor;	
				}	
			}
			//var_dump($query);
			$session = new Zend_Session_Namespace('paginator');
			$paginator = Core_Business_Training::getTrainingIterator($query);	
			$rows = $paginator->getPages();
			$editable  =$this->_helper->Acl->getUser()->getRole() == Core_Business_Rule::Customer ? true : false;
			$out=array();
			if(isset($rows)) {
				foreach ($rows as $item) {
					if($item->Paymentid != null) {
						$pay = $item->getPayment()->Label;
					}
					else { 
						$pay = "-";
					}
					
					//$out[]=array("id"=>$item->Id,"title"=>$item->Name,"detail"=>$item->Detail,"payment"=>$pay,"editabled"=>$editable);
					$out[]=array("id"=>$item->Id,"title"=>$item->Name,"payment"=>$pay,"Rule"=>$this->_helper->Acl->getUser()->getRole(),"User"=>$this->_helper->Acl->getUser()->LastName,"Created"=>$item->Created,"editabled"=>$editable);
				}
			}
			
			$output= array('data'=>$out,'nbpage'=>$paginator->getNbPage());
			$this->view->output = Zend_Json::encode($output);	
			$session = new Zend_Session_Namespace('paginator');
			$session->paginator = $paginator;
			
		}
	}
}
?>